package com.example.security;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.authentication.configurers.GlobalAuthenticationConfigurerAdapter;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import com.example.models.UserRole;
import com.example.models.Users;
import com.example.repositories.UserRoleRepository;
import com.example.repositories.UsersRepository;

@Configuration
class WebSecurityConfiguration extends GlobalAuthenticationConfigurerAdapter {

  @Autowired
  UsersRepository usersRepository;
  @Autowired
  UserRoleRepository userRoleRepository;
  
  @Override
  public void init(AuthenticationManagerBuilder auth) throws Exception {
    auth.userDetailsService(userDetailsService());
  }

  @Bean
  UserDetailsService userDetailsService() {
    return new UserDetailsService() {

      @Override
      public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        Users account = usersRepository.findByUsername(username);
        if(account != null) {
        	Collection<UserRole> userRoles = userRoleRepository.findByUsername(account.getUsername());
        	if(userRoles!=null){
        		List<GrantedAuthority> grantedAuthorities = new ArrayList<GrantedAuthority>();
        		for(UserRole ur: userRoles){
        			grantedAuthorities.add(new SimpleGrantedAuthority(ur.getRole()));
        		}
        		 return new User(account.getUsername(), account.getPassword(), account.isEnabled(), true, true, true,
//                       AuthorityUtils.createAuthorityList("USER"));
               		grantedAuthorities);
        	}
        	else{
        		throw new UsernameNotFoundException("could not find the roles for the user '"
                        + username + "'");
        	}
        } else {
          throw new UsernameNotFoundException("could not find the user '"
                  + username + "'");
        }
      }
      
    };
  }
}
